package controllers

import (
	"bytes"
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"github.com/jinzhu/gorm"
	"wjp/models"
	"wjp/syserror"
)

type NoteController struct {
	BaseController
}

func (this *NoteController) NextPrepare() {
	//fmt.Println("123")
	this.MustLogin()//用户必须登陆，没有登陆就返回错误
	if this.User.Role != 0 {//不是管理员，之前返回错误
		this.Abort500(syserror.NoPowewrError{})
		fmt.Println("您没有权限修改文章")
	}
}

//note
// @router /new [get]
func (this *NoteController)Index()  {

	this.Data["key"]=this.UUID()
	this.TplName="note_new.html"
}

// @router /save/:key [post]
func (this *NoteController)Save()  {
	key := this.Ctx.Input.Param(":key")
	//title  content
	title := this.getMustString("title","请输入标题！")
	content := this.getMustString("content","请输入内容！")

	note,err :=models.QueryNoteByKey(key)
	fmt.Println(note)
	fmt.Println(err)
	var n models.Note
	if err!=nil{
		if err== gorm.ErrRecordNotFound{
				n=models.Note{
					Key:key,
					Title:title,
					Content:content,
					UserID:int(this.User.ID),
					User:this.User,
				}
		}else{
			this.Abort500(syserror.New("保存失败",err))
		}
	}else{
		note.Title=title
		note.Content=content
		n=note
	}
	fmt.Println(n)
	//摘要逻辑
	n.Summary,_=getSummary(content)
	if err :=models.SaveNote(&n);err !=nil{
		this.Abort500(syserror.New("保存失败",err))
	}
	this.JsonOk("保存成功",fmt.Sprintf("/details/%s",key))
}

func getSummary(html string)(string, error){
	var bufbytes bytes.Buffer
	if _,err :=bufbytes.Write([]byte(html));err !=nil{
		return "",err
	}
	doc,err :=goquery.NewDocumentFromReader(&bufbytes)
	if err!=nil{
		return "",nil
	}
	htmlstr := doc.Find("body").Text()
	if(len(htmlstr)>=600){
		 htmlstr =htmlstr[:600]
	}
	return htmlstr,nil
}
//note
// @router /edit/:key [get]
func (this *NoteController)EditPage()  {

	key :=this.Ctx.Input.Param(":key")
	note,err :=models.QueryNoteByKeyAndUseid(key,int(this.User.ID))
	if err !=nil{
		this.Abort500(syserror.New("文章不存在",err))
	}

	this.Data["note"]=note
	this.Data["key"]=key

	this.TplName="note_new.html"
}

// @router /del/:key [post]
func (this *NoteController)Del()  {
	key := this.Ctx.Input.Param(":key")
	if err :=models.DeleteNoteByUserIDAndKey(key,int(this.User.ID));err !=nil{
		this.Abort500(syserror.New("删除失败",err))
	}
	this.JsonOk("删除成功","/")
}